#
# messkit.pys60_stream
#
# Copyright 2006 Helsinki Institute for Information Technology (HIIT)
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
Stream implementation for S60 phones

This uses the undocumented completion callbacks provided by the socket
implementation in PyS60.  It turns out to be a much nicer approach
than the Unix one of using an explicit, central select loop.

When using this implementation, you can and should omit the
callback_callback argument when initializing the StreamManager.

To listen for connections on the loopback interface, be sure to
specify an address of the form ('128.0.0.1", <port>).
"""

import socket
import errno

from messkit.stream import Stream as _Stream
from messkit.stream import StreamServer as _StreamServer
from messkit.stream import StreamManager as _StreamManager

__all__ = ['Stream', 'StreamServer', 'StreamManager']

SocketType = socket._socketobject # Missing from socket.py.

class Stream(_Stream):
    def _init(self, arg):
        if isinstance(arg, tuple):
            self.socket = socket.socket(*arg)
        elif isinstance(arg, SocketType):
            self.socket = arg
        else:
            raise TypeError

        self.flushing = False
        self.filling = False

    def _close(self, cb):
        # XXX Need to make sure this doesn't abort a pending flush.
        try:
            # It turns out that closing the socket doesn't close the
            # connection if there is a recv pending, so we do a
            # shutdown first.  It will raise an exception if the
            # connection has broken or has been shut down from the
            # other end, or if the socket has not been connected yet.
            self.socket.shutdown(2) # SHUT_RDWR
        except socket.error:
            pass

        self.socket.close()
        self.issue_callback(cb)

    def _connect(self, address, cb):
        def proxy(result):
            if not result:
                v = None
            else:
                t, v = result
                self.error = v

            self.issue_callback(cb, v)

        # XXX If connect() can raise network-related exceptions (can
        # it?), we should consider whether it would be better to turn
        # them into callbacks.  We can't use connect_ex() because it
        # isn't implemented.
        self.socket.connect(address, proxy)

    def _flush(self, buf):
        def step(n):
            if not isinstance(n, int):
                t, v = n
                self._signal_error(v)
                return          # Leave self.flushing set to True.

            self.bytes_out += n
            if buf.size:
                s = buf.read(self.send_size)
                self.socket.sendall(s, 0, step)
            else:
                self.flushing = False

        if not self.flushing:
            self.flushing = True
            step(0)

    def _fill(self, buf, size, cb):
        def step(s):
            assert not self.eof_seen
            if not isinstance(s, str):
                t, v = s
                if v[0] == errno.EPIPE:
                    # I have been seeing this on the loopback when the
                    # other end does a normal close, so let's treat it
                    # as an EOF instead of as an error.
                    self.eof_seen = True
                else:
                    self._signal_error(v)
                    return      # Leave self.filling set to True.
            elif not s:
                self.eof_seen = True
            else:
                self.bytes_in += len(s)
                buf.append(s)

            if self.bytes_in < stop and not self.eof_seen:
                self.socket.recv(self.recv_size, 0, step)
            else:
                self.filling = False
                self.issue_callback(cb, self.bytes_in - start)

        assert not self.filling
        if self.eof_seen:
            self.issue_callback(cb, 0)
        else:
            self.filling = True
            start = self.bytes_in
            stop = start + size
            self.socket.recv(self.recv_size, 0, step)

class StreamServer(_StreamServer):
    def _init(self, socket_params):
        self.socket_params = socket_params
        self.socket = socket.socket(*socket_params)

    def _close(self, cb):
        self.socket.close()
        self.issue_callback(cb)

    def _listen(self, address):
        # For TCP, the address should be of the form ('127.0.0.1', <port>).
        self.socket.bind(address)
        self.socket.listen(5)

    def _accept(self, cb):
        def proxy((e32sock, addr)):
            family = self.socket_params[0]
            sock = socket._socketobject(e32sock, family)
            self.issue_callback(cb, sock, addr)

        self.socket.accept(proxy)

class StreamManager(_StreamManager):
    def __init__(self, callback_callback=None):
        # The caller can and should omit the callback argument.
        if callback_callback is None:
            callback_callback = lambda f: f()
        _StreamManager.__init__(self, callback_callback)

    def _create_stream(self, *args):
        return Stream(self, *args)

    def _create_server(self, socket_params):
        return StreamServer(self, socket_params)
